import {index} from './utils.js';

let sortableInstanceOptions;
const initSortableThis = (options) => {
	sortableInstanceOptions = options;
}

const isDomElement = value => {
	return (
		value &&
		typeof value === 'object' &&
		value.nodeType === 1 &&
		typeof value.nodeName === 'string'
	)
}

/**
 * 获取dom所在的位置
 * @param {Element} dom
 * @param key
 * @returns {number[][]} [[1,2],[1,3]]
 */
const getPosition = (dom, key = 'data-pos') => {
	return sortableInstanceOptions.utils.getPosition(dom)
	// if (!isDomElement(dom)) return null
	// const pos = dom.getAttribute(key)
	// return pos ? JSON.parse(pos) : null
}


/**
 *
 * @param {Element} dragEl 拖元素的dom
 * @param {Element} dropEl 放元素的dom
 * @returns {String} 拖拽的方向
 */
const getDirection = (dragEl, dropEl) => {
	const dragPosition = getPosition(dragEl)
	const dropPosition = getPosition(dropEl)
	if (!dragPosition || !dropPosition) return 'horizontal'

	const dragHorizontalPos = [...new Set(dragPosition.map(pos => pos[0]))]
	const dropHorizontalPos = [...new Set(dropPosition.map(pos => pos[0]))]

	return dragHorizontalPos[0] !== dropHorizontalPos[0]
		? combineArray(
			dragHorizontalPos,
			dropHorizontalPos,
			dragPosition,
			dropPosition
		)
		: 'horizontal'

	function combineArray(arr1, arr2, arr11, arr22) {
		const groupArray = [
			[0, 1],
			[2, 3],
			[4, 5]
		]
		const groupMap = {}

		for (const group of groupArray) {
			for (const num of group) {
				groupMap[num] = group
			}
		}

		const groupOfArr1 = findGroup(arr1)
		const groupOfArr2 = findGroup(arr2)
		const commonValues = [arr1.filter(value => arr2.includes(value))].sort()

		if (!areArraysEqual(groupOfArr1, groupOfArr2)) {
			// console.log('arr1, arr2', arr11, arr22)
			// 还差纵向斜着拖拽
			return 'vertical-across-rows'
		} else {
			if (commonValues.length > 0 && commonValues[0].length > 0) {
				if (arr1.length === 1 && arr1[0] % 2 === 1) {
					return 'vertical-drag'
				}
				if (arr2.length === 1 && arr2[0] % 2 === 1) {
					return 'vertical-drop'
				}
			}
			return 'vertical'
		}

		function findGroup(arr) {
			for (const num of arr) {
				if (groupMap[num]) {
					return groupMap[num]
				}
			}
			return null
		}
	}
}

/**
 *
 * @param {number[][]} arr1 [1,2]
 * @param {number[][]} arr2 [2,1]
 * @returns {Boolean}
 */
function areArraysEqual(arr1, arr2) {
	return sortableInstanceOptions.utils.areArraysEqual(arr1, arr2)
}


/**
 * 将两个元素进行交换
 * @param {Element} n1
 * @param {Element} n2
 * @returns void
 */
function swapNodes(n1, n2) {
	let p1 = n1.parentNode,
		p2 = n2.parentNode,
		i1,
		i2

	if (!p1 || !p2 || p1.isEqualNode(n2) || p2.isEqualNode(n1)) return

	i1 = index(n1)
	i2 = index(n2)

	if (p1.isEqualNode(p2) && i1 < i2) {
		i2++
	}
	p1.insertBefore(n2, p1.children[i1])
	p2.insertBefore(n1, p2.children[i2])
}

function getElement(el, flag = true) {
	const dragPos = getPosition(el)
	const eventPos = dragPos.map(v => [v[0] - 1, v[1]])
	// console.log('eventPos', eventPos)
	for (let i = 0; i < el.parentNode.children.length; i++) {
		if (areArraysEqual(eventPos, getPosition(el.parentNode.children[i]))) {
			return el.parentNode.children[i]
		}
	}
}

function fillArray(fromPos, toPos, from, to) {
	// console.log('fromPos, toPos', fromPos, toPos, from, to)
	if (fromPos.length === 0 || toPos.length === 0) {
		return null
	}

	const utils = sortableInstanceOptions.utils;
	const getSize = utils.getSize;
	const getRootVars = utils.getRootVars;


	// let i = 0
	const maxPosDom = fromPos.length > toPos.length ? from : to
	const minPosDom = fromPos.length > toPos.length ? to : from


	const maxData = getSize(index(maxPosDom))
	const [rows, cols] = utils.getRowAndCol(maxData.widgetSize)
	const minData = getSize(index(minPosDom))
	let [row, col] = minData.fill[0][0] % 2 === 1 ? [minData.fill[0][0] - 1, minData.fill[0][1]] : minData.fill[0]
	if (col + cols > getRootVars.iconCol) {
		console.log('不满足往后找')
		col = getRootVars.iconCol - cols;
	}


	// while (fromPos.length !== toPos.length && i < 1) {
	let doms = {
		odd: [],
		even: [],
	}

	let indexes = {
		min: {
			odd: [],
			even: []
		},
		max: []
	}
	indexes.max.push(index(maxPosDom))
	for (let i = 0; i < rows; i++) {
		for (let j = 0; j < cols; j++) {
			const blockRow = row + i;
			const blockCol = col + j;
			const dom = getElementbyPos(to, [blockRow, blockCol]);
			if (!doms.odd.includes(dom) && !doms.even.includes(dom)) {
				if (blockRow % 2 === 0) {
					doms.odd.push(dom)
					indexes.min.odd.push(index(dom))
				} else {
					doms.even.push(dom)
					indexes.min.even.push(index(dom))
				}
			}
		}
	}

	return {doms, maxPosDom, indexes}
}

function getElementbyPos(toEl, pos) {
	const childrens = Array.from(toEl.parentNode.children)
	const dom = childrens.find(el => getPosition(el).some(vpos => {
		return vpos[0] === pos[0] && vpos[1] === pos[1]
	}))
	return dom ? dom : null
}

function previousElementSiblingDeep(el, deepth = 1) {
	let index = 0;

	while (deepth >= index) {
		index++;
		el = el.previousElementSibling
	}
}

export {getPosition, getDirection, swapNodes, getElement, fillArray, initSortableThis}
